/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : booking_write.js                                 
*  Description  : 부킹게시판 글작성 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-03  김효순    Created.  
*  2012-05-03  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 제목
	function clsTitle()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE": "제목을 입력해 주십시요."
			, "_MAXLENTH": "한글 30자 이내로 입력해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsTitle.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dl.golf_write02 input:text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].val(val);
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, isValid: function(){
			if(this.getValue() == ""){
				this.errMsg = "_NOVALUE";
				return false;
			}else if(_util.getByteLen(this.getValue()) > 60){
				this.errMsg = "_MAXLENTH";
				return false;
			}
			
			return true;
		}
		, focus: function(){
			this._HTMLDom["$layer"].trigger("focus");
		}
	}
	
	// 내용
	function clsNote()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsNote.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dd.img_g");
			var thisClass = this;
			
			this._HTMLDom = {
				"$layer": $layer
			}
			
			var $tmp = $layer.children().clone(true);
			
			$layer.html("<textarea></textarea>").append($tmp);
			
			fnLoadingJS("../inc/ckeditor_3.6.3/ckeditor.js", function(){
				fnLoadingJS("../inc/ckeditor_3.6.3/adapters/jquery.js", function(){
					thisClass._CKEditor();
				});
			});
		}
		, _CKEditor: function(){
			var thisClass = this;
			
			this._HTMLDom["$layer"].find("textarea").ckeditor(document.objGlobal.getCKOption());
			
			// 에디터 준비완료
			this.$getEditor().ckeditorGet().on("instanceReady", function(){
				_gf.setCKEditorUploadFileButton(this, function(ret){
					document.objControl.finishUploadFile(ret);
				});
			});
		}
		, focus: function(){
			this.$getEditor().ckeditorGet().focus();
		}
		, $getEditor: function(){
			return this._HTMLDom["$layer"].find("textarea");
		}
		, getValue: function(){
			return this.$getEditor().val();
		}
		, setValue: function(val){
			this.$getEditor().val(val);
		}
		, insertImage: function(szImage){
			this.$getEditor().ckeditorGet().insertHtml("<img src='" + szImage + "' />");
		}
	}
	
	// 업로드파일
	function clsUploadFile()
	{
		this.listData = null;
		
		this._init();
	}
	
	clsUploadFile.prototype = {
		_init: function(){
			this.setList([]);
		}
		, setList: function(thisData){
			this.listData = thisData;
		}
		, push: function(oneData){
			if(!oneData["파일키"]) oneData["파일키"] = "NOT";
			if(!oneData["섬네일"]) oneData["섬네일"] = "NOT";
			
			this.listData.push(oneData);
		}
		, getList: function(){
			return this.listData;
		}
		, sync: function(note){
			for(var i=0;i<this.listData.length;i++){
				var targetURL = "";
				targetURL = _gf.filePath2Url(this.listData[i]["파일명"]);
				
				var reg = new RegExp(targetURL, "gi");
				
				if(!reg.test(note)){
					this.listData.splice(i, 1);
					i--;
				}
			}
		}
		, getValue: function(){
			var szRet = "";
			for(var i=0;i<this.listData.length;i++){
				if(szRet) szRet += ",";
				
				szRet += this.listData[i]["파일키"] + "," + this.listData[i]["섬네일"] + "," + this.listData[i]["파일명"] + "," + this.listData[i]["원본파일명"];
			}
			
			return szRet;
		}
	}
	
	function clsComm()
	{
		this.bookingRequest = null;
		this.bookingData = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.bookingData = {
				"제목": null
				, "내용": null
			}
			
			this.bookingRequest = {
				"키": null
			}
		}
		, setBookingRequest: function(key, val){
			this.bookingRequest[key] = val;
		}
		, getBookingInfo: function(){
			var thisClass = this;
			
			//ajax
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": "getDetailBookingBoard"
			}, {
				"board_seq": this.bookingRequest["키"]
				, "modpage_yn": "Y"
			}, function(ret){
				
				if(ret["msp"]["contents"]["serviceResult"] == "00000"){
					var obj = ret["msp"]["contents"]["items"];
					var reg_date = obj["reg__date"]+"";
					var reg_time = obj["reg__time"]+"";
					var fileBean = obj["FileBean"];
					
					var aFileList = [];
					
					if(fileBean){
						for(var i=-0;i<fileBean.length;i++){
							var objFile = fileBean[i]["items"];
							aFileList.push({
								"파일키": objFile["file__seq"]
								, "섬네일": objFile["thumb"]
								, "파일명": objFile["path"] + objFile["save__file__name"]
								, "원본파일명": objFile["orgn__file__name"]
							});
						}
					}
					
					thisClass.bookingData = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "제목": obj["title"]
						, "내용": obj["content"]
						, "내꺼여부": "Y"
						, "파일리스트": aFileList
					}
				}else{
					thisClass.bookingData = {
						"결과코드": ret["msp"]["contents"]["serviceResult"]
						, "메시지": document.objGlobal.getResultMsg(ret)
					}
				}
				
				document.objControl.finishBookingInfo();
			});
		}
		, getBookingData: function(){
			return this.bookingData;
		}
		, bookingSubmit: function(arg){
			var thisClass = this;
			
			// ajax
			var serviceName = (arg["키"]) ? "updateBookingBoard":"regBookingBoard";
			document.objGlobal.ajax({
				"sid": "BB001",
				"servicename": serviceName
			}, {
				"board_seq": arg["키"]
				, "content": _util.ajaxTrans(arg["내용"])
				, "title": _util.ajaxTrans(arg["제목"])
				, "notice_yn": "N"
				, "file_list": arg["파일리스트"]
			}, function(ret){
				document.objControl.finishBookingSubmit({
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				});
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objTitle = null;
		this.objNote = null;
		this.objUploadFile = null;
		
		this.bookingKey = document.objUtil.getParam("q_seq");
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objTitle = new clsTitle();
			this.objNote = new clsNote();
			this.objUploadFile = new clsUploadFile();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var k in thisClass._permistStart){
					if(!thisClass._permistStart[k]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			})
		}
		, _bind: function(){
			var thisClass = this;

			// 글작성
			$("div#container section#main_content a").has("img[alt=확인]").click(function(){
				if(!thisClass.objTitle.isValid()){
					alert(thisClass.objTitle.getError());
					thisClass.objTitle.focus();
					return;
				}
				
				thisClass.objUploadFile.sync(thisClass.objNote.getValue());
				var szUploadFile = thisClass.objUploadFile.getValue();
				
				document.objGlobal.spinStart("sending...");
				thisClass.objComm.bookingSubmit({
					"키": thisClass.bookingKey
					, "제목": thisClass.objTitle.getValue()
					, "내용": thisClass.objNote.getValue()
					, "파일리스트": szUploadFile
				});
			});
			
			// 취소
			$("div#container section#main_content img[alt='취소']").click(function(){
				if(thisClass.bookingKey){
					thisClass.goViewPage();
				}else{
					thisClass.goListPage();
				}
			});
		}
		, _start: function(){
			// 글정보 받아오기
			if(_util.getParam("q_seq")){
				_gf.spinStart("receiving...");
				
				this.objComm.setBookingRequest("키", this.bookingKey);
				this.objComm.getBookingInfo();
			}
		}
		// 글작성 완료
		, finishBookingSubmit: function(ret){
			_gf.spinEnd();
			
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			if(_util.getParam("q_seq")){
				this.goViewPage();
			}else{
				this.goListPage();
			}
		}
		// 수정모드시 데이터 받아오기 완료
		, finishBookingInfo: function(){
			var thisData = this.objComm.getBookingData();
				
			_gf.spinEnd();
			
			this.objTitle.setValue(thisData["제목"]);
			this.objNote.setValue(thisData["내용"]);
			this.objUploadFile.setList(thisData["파일리스트"]);
		}
		// 이미지 업로드
		, finishUploadFile: function(ret){
			var fs = ret["파일리스트"][0]["파일크기"]-0;
			
			if(fs >= 1 * 1024 * 1024){
				alert("사진용량은 1장당 1MB까지만 등록 가능합니다. 파일 용량을 확인하여 주세요.");
				return;
			}
			
			this.objNote.insertImage(_gf.filePath2Url(ret["파일리스트"][0]["파일명"]));
			//this.objNote.insertImage(ret["파일리스트"][0]["파일명"].replace(_UPLOADPATH_TMP, _UPLOADURL_TMP));

			this.objUploadFile.push(ret["파일리스트"][0]);
		}
		// 리스트이동
		, goListPage: function(){
			document.location.href = "booking.html" + _util.paramStringFilter(["q_seq"]);
		}
		// 보기이동
		, goViewPage: function(){
			document.location.href = "booking_view.html" + _util.paramStringFilter([]);
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});